# coding:utf-8
from django.shortcuts import render
# from utils import models
from django.http import HttpResponse
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import StreamingHttpResponse
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
import MySQLdb
from django.http import JsonResponse
import time
from .db import lagou_post_info ,search_info
from utils.models import *

# Create your views here.

def setSession(request):
    pno = request.GET['pno']
    cno = request.GET['cno']
    request.session['pno'] = str(pno)
    request.session['cno'] = str(cno)
    data = {'status': 0, 'msg': 'true'}
    return JsonResponse(data)


def getdata(sql):
    conn = MySQLdb.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='wearetvxq5',
        db='website',
        charset='utf8',
    )
    cur = conn.cursor()
    cur.execute(sql)
    index = cur.description
    result = []
    for res in cur.fetchall():
        row = []
        for i in range(len(index)):
            row.append(res[i])
        result.append(row)
    return result


def getdescription(sql):
    conn = MySQLdb.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='mysql123',
        db='website',
        charset='utf8',
    )
    cur = conn.cursor()
    cur.execute(sql)
    return cur.description


def getcity(request):
    pno = request.GET['procode']
    citys = Cities.objects.filter(pno=str(pno))
    data = serializers.serialize('json', citys)
    return HttpResponse(data, content_type='application/json')


def getarea(request):
    no = request.GET['cityno']
    areas = Areas.objects.filter(cno=str(no))
    data = serializers.serialize('json', areas)
    return HttpResponse(data, content_type='application/json')


def getsecondindustry(request):
    no = request.GET['code']
    second = Industy.objects.filter(pre=str(no))
    data = serializers.serialize('json', second)
    return HttpResponse(data, content_type='application/json')


# --------------------------------------------------------------------
#
# dataset=getdata("SELECT c.`name` as cname,p.name as pname,p.salary,p.grad,a.`name` as area,p.date FROM utils_position p,utils_company c,utils_areas a WHERE p.compno=c.id AND p.loc=a.code ")
dataset = lagou_post_info.select()


def get_position_page(request):
    global dataset
    print(dataset.count())

    n = request.GET["index"]
    index = int(n)
    data = dataset.paginate(index, 9)  # desc

    datas = []
    for item in data:
        # data = {
        #     "1": item.company,
        #     "b": item.post_name,
        #     "c": item.salary,
        #     "d": item.education,
        #     "e": item.city,
        #     "f": item.publish_time,
        #
        # }

        education_dict={
            "博士":"0",
            "硕士": "1",
            "本科": "2",
            "专科": "3",
            "大专": "4",
            "高中": "5",
            "其他": "6",
            "经验不限": "6",
            "不限": "6",
            "中专及以下": "6",
            "学历不限": "6",


        }
        data = [item.company,
                item.post_name,
                item.salary,
                education_dict[item.education.replace(" ","")],
                item.city,
                item.publish_time,
                item.id]
        print(data)
        datas.append(data)

    data = {'status': 0, 'msg': '请求成功', 'data': datas}
    return JsonResponse(data)


# 这个才是详细页面
def job_search(request):
    print('???')
    indus = str(request.GET["indus"])  #D45 职位  根据表 换回中文
    salary = str(request.GET["salary"])  #薪水
    loc = str(request.GET["loc"])   # 区  地址标记的最后一栏  而且可能有空格
    grad = str(request.GET["grad"])  #数字
    type = str(request.GET["type"])  #(请选择 实习 全职)
    keyword = str(request.GET["keyword"]) #搜索词

    global dataset
    
    if (indus != '-1' and indus != '') or \
            (salary != '-1' and salary != '') or \
            (grad != '-1' and grad != '') or \
            (type != '-1' and type != '') \
            or (keyword != '-1' and keyword != ''):
        dataset = lagou_post_info.select()
        print(dataset.count())
        if keyword != '-1' and keyword != '':
            posttime = int(time.time())
            timeArray = time.localtime(posttime)
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            search_info.insert(name=keyword, updated_at=otherStyleTime).execute()

            #  厂家 条形码  入库人 均为字符串赛选
            print(keyword)
            like = '%' + keyword + '%'
            dataset = dataset.where((lagou_post_info.post_name % like) |
                              (lagou_post_info.company % like) |
                              (lagou_post_info.industry % like) |
                              (lagou_post_info.key_word % like))
        if loc != '-1' and loc != '':
            qu_id = Areas.objects.get(name=loc)
            shi_id = Cities.objects.get(code=qu_id.cno)
            if shi_id.name == '县':
                sheng_id = Provinces.objects.get(code=shi_id.pno)
                shi = sheng_id.name.replace('市', '')
            if shi_id.name == '市辖区':
                sheng_id = Provinces.objects.get(code=shi_id.pno)
                shi = sheng_id.name.replace('市', '')
            dataset=dataset.where(lagou_post_info.city==shi)
            print(dataset.count())



        if grad != '-1' and grad != '':
            education_dict = {
                "1": "博士",
                "2": "硕士",
                "3": "本科",
                "4": "专",  # 还要大专
                "5": "高中",
                "6": "不限",  # 对应库里的不限
            }
            grad = education_dict[grad]
            like = '%' + grad + '%'
            dataset = dataset.where(lagou_post_info.education % like)

        if salary != '-1' and salary != '':
            salary_dict = {
                "1": "0 5",
                "2": "5 10",
                "3": "10 15",
                "4": "0 1",  # 还要大专
                "5": "9 13",
                "6": "13",
                "7": "13",
                "8": "13",# 对应库里的不限
            }
            if salary== '6':
                min='13'
                dataset=dataset.where(lagou_post_info.min >= min)
            else:
                min=salary_dict[salary].split(' ')[0]
                max=salary_dict[salary].split(' ')[1]

                dataset = dataset.where(lagou_post_info.min_code >= int(min))
                dataset = dataset.where(lagou_post_info.max_code <= int(max))
                    # ((lagou_post_info.min >= min) &(lagou_post_info.max <= min)) |
                    # ((lagou_post_info.min <= max) & (lagou_post_info.max >= max)))

    datass = dataset.paginate(1, 9)  # desc

    datas = []
    for item in datass:
        education_dict = {
            "博士": "0",
            "硕士": "1",
            "本科": "2",
            "本科 ": "2",
            "专科": "3",
            "大专": "4",
            "大专 ": "4",
            "高中": "5",
            "其他": "6",
            "经验不限": "6",
            "不限": "6",
            "中专及以下": "6",

        }
        data = [item.company,
                item.post_name,
                item.salary,
                education_dict[item.education],
                item.city,
                item.publish_time, item.id]
        print(data)
        datas.append(data)
    data = {'count': dataset.count(), 'len': dataset.count()/9, 'data': datas}
    return JsonResponse(data)


def get_firm_page(request):
    n = request.GET["index"]
    index = int(n)
    sql = "SELECT c.name,c.loc,COUNT(*),p.date FROM utils_position p,utils_company c WHERE c.id=p.compno GROUP BY p.compno"
    firmlist = getdata(sql)
    if (index * 9 < len(firmlist)) and (index >= 1):
        temp = (index - 1) * 9
        data = firmlist[temp:temp + 9]
    elif index == 1:
        data = firmlist[0:9]
    else:
        temp = len(firmlist) - (index - 1) * 9 + 1
        data = firmlist[temp:len(firmlist)]
    data = {'status': 0, 'msg': '请求成功', 'data': data}
    return JsonResponse(data)


def get_job_page(request):
    n = request.GET["index"]
    index = int(n)
    sql = "SELECT c.`name` as cname,p.name as pname,p.salary,p.grad,a.`name` as area,p.date FROM utils_position p,utils_company c,utils_areas a WHERE p.compno=c.id AND p.loc=a.code "
    position = getdata(sql)
    paginator = Paginator(position, 9)
    try:
        data = paginator.page(index)
    except PageNotAnInteger:
        data = paginator.page(1)
    except EmptyPage:
        data = paginator.page(paginator.num_pages)
    temp = serializers.serialize('json', data)
    return HttpResponse(temp, content_type='application/json')


def getdeliverpage(request):
    n = request.GET["index"]
    index = int(n)
    dataset = Application.objects.all()
    paginator = Paginator(dataset, 9)
    try:
        data = paginator.page(index)
    except PageNotAnInteger:
        data = paginator.page(1)
    except EmptyPage:
        data = paginator.page(paginator.num_pages)
    temp = serializers.serialize('json', data)
    return HttpResponse(temp, content_type='application/json')


# 生成简历pdf
def get_info():
    c = canvas.Canvas("media/info.pdf")
    c.drawString(-100, -100, "resume")
    c.drawString(10, 10, "name")
    c.drawString(20, 10, "name")
    c.drawString(30, 10, "name")
    c.drawString(40, 10, "name")
    c.drawString(50, 10, "name")
    c.drawString(60, 10, "name")
    c.drawString(10, 30, "XXX")
    c.drawString(20, 30, "XXX")
    c.drawString(30, 30, "XXX")
    c.drawString(40, 30, "XXX")
    c.drawString(50, 30, "XXX")
    c.drawString(60, 30, "XXX")
    c.showPage()
    c.save()


def info_download(request):
    get_info()

    # do something...
    def file_iterator(file_name, chunk_size=1024):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    the_file_name = "media/info1.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
    return response


def toudi(request):
    pn = request.GET['pno']
    un = request.session.get('userID')
    if str(un).strip() != "":
        user = Jobseeker.objects.get(emill=str(un))
        data = {'pos_no': int(pn),
                'uno': int(user.id),
                'date': str(time.strftime('%Y-%m-%d', time.localtime(time.time()))),
                'state': 0
                }
        Application.objects.create(**data)
        data = {'status': 0, 'msg': 'true'}
    else:
        data = {'status': 0, 'msg': 'false'}
    return JsonResponse(data)


def get_desc_position(request):
    n = request.GET["index"]
    index = int(n)
    cno = request.session.get('cno')
    firm = Company.objects.get(name=str(cno))
    sql = "SELECT p.name,p.salary,p.grad,a.name,p.date FROM utils_position p,utils_areas a WHERE a.code=p.loc AND p.compno=%d" % int(
        firm.id)
    positionlist = getdata(sql)
    if (index * 9 < len(positionlist)) and (index >= 1):
        temp = (index - 1) * 9
        data = positionlist[temp:temp + 9]
    elif index == 1:
        data = positionlist[0:9]
    else:
        temp = len(positionlist) - (index - 1) * 9 + 1
        data = positionlist[temp:len(positionlist)]
    data = {'status': 0, 'msg': '请求成功', 'data': data}
    return JsonResponse(data)
